//
//  COBaseAlertView.swift
//  CocoProject
//
//  Created by Vill on 2023/11/7.
//

import UIKit

typealias CloseBlock = (() -> Void)
typealias VoidBlock = (() -> Void)

enum BaseAlertType {
    case Center
    case TopRight
    case TopLeft
    case Top
    case Bottom
}

class COBaseAlertView: UIView {

    var dismissBlock:VoidBlock?
    var closeBlock:CloseBlock?
    
    private var type:BaseAlertType = .Center
    var blankView:UIView?
    var contentView:UIView?
    var isAppear:Bool = false
    
    var contentWidth:CGFloat = 0{
        didSet {
            if((self.contentView) != nil){
                self.contentView?.snp.remakeConstraints { make in
                    make.width.equalTo(self.contentWidth)
                }
            }
        }
    }
    
    lazy var closeBtn: UIButton = {
        let close = UIButton(type: .custom)
        close.setImage(KImaged("coco_alert_close"), for: .normal)
        close.addTarget(self, action: #selector(closeAction), for: .touchUpInside)
        return close
    }()
    
    init(type:BaseAlertType = .Center) {
        super.init(frame: .zero)
        self.contentWidth = SCREENWIDTH - PTW(40)
        self.type = type
        self.blankView = UIView.init()
        self.blankView?.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        self.blankView?.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(blankViewTap)))
        self.addSubview(self.blankView!)
        self.blankView?.snp.makeConstraints({ make in
            make.edges.equalToSuperview()
        })
        self.contentView = UIView.init()
        self.contentView?.layer.cornerRadius = PTW(20)
        self.contentView?.layer.masksToBounds = true
        self.contentView?.backgroundColor = UIColor.white
        self.addSubview(self.contentView!)
        self.addSubview(self.closeBtn)
        self.closeBtn.snp.makeConstraints { make in
            make.size.equalTo(PTW(40))
            make.centerX.equalToSuperview()
            make.top.equalTo(self.contentView!.snp.bottom).offset(PTW(30))
        }
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(noti:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(noti:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func keyboardWillShow(noti:Notification){
        if(self.type != .Center){return}
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
            self.contentView?.snp.remakeConstraints({ make in
                make.centerX.equalToSuperview()
                make.width.equalTo(self.contentWidth)
                make.top.equalTo(self).offset(statusBarHeight)
            })
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
                self.layoutIfNeeded()
            }
        })
    }
    
    @objc func keyboardWillHide(noti:Notification){
        if(self.type != .Center){return}
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
            self.contentView?.snp.remakeConstraints({ make in
                make.center.equalToSuperview()
                make.width.equalTo(self.contentWidth)
            })
            UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut) {
                self.layoutIfNeeded()
            }
        })
    }
    
    @objc func closeAction(){
        dissMiss()
        if (self.closeBlock != nil) {
            self.closeBlock!()
        }
    }
    
    @objc func blankViewTap(){
        dissMiss()
        if (self.closeBlock != nil) {
            self.closeBlock!()
        }
    }
    
    public func show(){
        self.showInView(view: UIApplication.shared.getKeyWindow()!)
    }
    
    deinit{
        NotificationCenter.default.removeObserver(self)
    }
    
    func showInView(view:UIView){
        self.isAppear = true
        self.alpha = 1
        view.endEditing(true)
        view.addSubview(self)
        self.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        switch self.type {
        case .Center:
            self.contentView?.snp.remakeConstraints { make in
                make.width.equalTo(self.contentWidth)
                make.centerX.equalTo(self)
                make.centerY.equalTo(self).offset(-PTW(35))
            }
            break
        case .TopLeft:
            self.contentView?.snp.remakeConstraints { make in
                make.width.equalTo(self.contentWidth)
                make.left.equalTo(self)
                make.top.equalTo(self).offset(statusBarHeight)
            }
            break
        case .TopRight:
            self.contentView?.snp.remakeConstraints { make in
                make.width.equalTo(self.contentWidth)
                make.right.equalTo(self)
                make.top.equalTo(self).offset(statusBarHeight)
            }
            break
        case .Top:
            self.contentView?.snp.remakeConstraints { make in
                make.right.equalTo(-PTW(10))
                make.left.equalTo(PTW(10))
                make.top.equalTo(self).offset(statusBarHeight)
            }
            break
        case .Bottom:
            self.contentView?.snp.remakeConstraints { make in
                make.left.equalTo(PTW(10))
                make.right.equalTo(-PTW(10))
                make.bottom.equalTo(self).offset(-statusBarHeight)
            }
            break
        }
        let animation = CAKeyframeAnimation(keyPath: "transform")
        animation.duration = 0.4
        animation.values = [NSValue(caTransform3D: CATransform3DMakeScale(0.01, 0.01, 1.0)),
                            NSValue(caTransform3D: CATransform3DMakeScale(1.1, 1.1, 1.0)),
                            NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)),
                            NSValue(caTransform3D: CATransform3DIdentity)]
        animation.keyTimes = [0.0,0.5,0.75,1]
        animation.timingFunctions = [CAMediaTimingFunction(name: .easeInEaseOut),
                                     CAMediaTimingFunction(name: .easeInEaseOut),
                                     CAMediaTimingFunction(name: .easeInEaseOut)]
        self.contentView?.layer.add(animation, forKey: nil)
        self.closeBtn.layer.add(animation, forKey: nil)
    }
    
    func dissMiss(){
        self.isAppear = false
        NotificationCenter.default.post(name: .RandomTimeRunNotification, object: nil, userInfo: ["type":0])
        UIView.animate(withDuration: 0.2, delay: 0,options: .curveLinear) {
            self.alpha = 0
        } completion: { finished in
            self.removeFromSuperview()
        }
        if (self.dismissBlock != nil) {
            self.dismissBlock!()
        }
    }

}
